package controllers

import (
	"accx/appFramework/m_config"
	"accx/models/accx"
	"accx/models/sync"
	"github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AccList(c *gin.Context) {
	seelog.Info("recivice a AccList request")
	acclist := accx.GetAcclist()
	code := http.StatusOK
	respMsg := accx.ResponseSucMsg{Code: 200}
	respMsg.Code = code
	respMsg.Data = acclist
	c.JSON(code, respMsg)
}
func HandShake(c *gin.Context) {
	var dynamicData sync.DynamicData
	var service []sync.Service
	seelog.Info("recivice a HandShake request")
	code := http.StatusOK
	respMsg := accx.ResponseSucMsg{Code: 200}
	var reqData accx.HandShake
	err := c.ShouldBindJSON(&reqData)
	if err != nil {
		seelog.Error("failed to get request data: ", err)
		code = http.StatusGatewayTimeout
		respMsg.Code = code
		respMsg.Message = "Accx timeout"
		goto END
	}
	if reqData.Authentication() == false {
		seelog.Error("Handshake failed to Authentication")
		return
	}
	if false == accx.PeerSmfRegist(reqData.Group, reqData.Node) {
		seelog.Error("peer smf regist error")
	}
	if false == accx.PeerAmfRegist(reqData.Group, reqData.Node) {
		seelog.Error("peer amf regist error")
	}
	if reqData.Status == m_config.LostConnection {
		//继承重选
	}
	//TODO：同步全量动态数据
	dynamicData.GetUDM()
	service = append(service, sync.Service{
		IP:   reqData.IP,
		Port: 2444,
	})
	dynamicData.BroadcastRequest(service)
END:
	c.JSON(code, respMsg)
}
func Heartbeat(c *gin.Context) {
	seelog.Info("recivice a Heartbeat request")
	code := http.StatusOK
	respMsg := accx.ResponseSucMsg{Code: 200}
	var reqData accx.Heartbeat
	err := c.ShouldBindJSON(&reqData)
	if err != nil {
		seelog.Error("failed to get request data: ", err)
		code = http.StatusGatewayTimeout
		respMsg.Code = code
		respMsg.Message = "Accx timeout"
		goto END
	}
	if reqData.Authentication() == false {
		seelog.Error("Heart failed to Authentication")
		return
	}
	if reqData.SaveHeartData() == false {
		seelog.Error("Heart save to Authentication")
		return
	}
END:
	c.JSON(code, respMsg)
}
